import warnings
import csv
import openpyxl
import numpy as np

from sql_db import select_bypage,select_byname

warnings.filterwarnings("ignore")
import pandas as pd
import os

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'

from flask import Flask, jsonify, request, render_template, make_response

import argparse
from static import data_lstm

# 搭建flask框架
app = Flask(__name__)


@app.route('/')  # 路径
def display_data():
    # 从本地 CSV 文件读取数据
    res = select_bypage(0, 9)
    print(res)
    # 将数据传递给html
    return render_template('FoundationPitMonitoring.html', data=res)


# 通过使用 @app.after_request 装饰器，add_header() 函数将在每个请求之后自动调用，并对响应进行处理。在示例中，它会为响应添加自定义的头部信息。
@app.after_request
# 跨域不加会报错
# ajax：No 'Access-Control-Allow-Origin' header is present on the requested
def cors(environ):
    environ.headers['Access-Control-Allow-Origin'] = '*'
    environ.headers['Access-Control-Allow-Method'] = '*'
    environ.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return environ

# @app.route('/select', methods=['GET', 'POST'], strict_slashes=False)
# def select():
#     if request.method == 'POST':
#         # # 获取 Ajax 传递的数据
#         DM_name = request.json['DM_name']
#         print('select',DM_name)
#         dbid = select_byname(DM_name)
#         print('select', dbid)
#         return jsonify({'dbid': dbid})

@app.route('/data', methods=['GET', 'POST'], strict_slashes=False)
def index():
    if request.method == 'POST':
        # # 获取 Ajax 传递的数据
        DM_name = request.json['DM_name']
        print(DM_name)

        dbid = select_byname(DM_name)
        dbid = dbid[0][0]
        print('select', dbid)

        # 进行模型预测
        dataset, predict_train_plot, predict_validation_plot, predict_60_plot = data_lstm.main(DM_name)
        # print(predict_train_plot)
        # print(predict_validation_plot)
        # processed_data = process_data(data)
        dataset = arr_change('dataset', dataset)
        predict_train = arr_change('predict_train', predict_train_plot)
        predict_validation = arr_change('predict_validation', predict_validation_plot)
        predict_60_plot = arr_change('predict_60', predict_60_plot)
        # print(predict_train)
        # print(predict_validation)
        # print(predict_60_plot)
        combined_list = combined_data(dataset, predict_train, predict_validation, predict_60_plot)
        # print(combined_list)

        # 返回处理后的数据到 Ajax
        return jsonify({'processed_data': combined_list,'dbid':dbid})


# # 如果是 GET 请求，返回初始 HTML 页面
# return render_template('template.html')

def arr_change(name, data):
    # 将NaN转换为空字符串
    data_processed = np.where(np.isnan(data), None, data)

    # 构建字典列表
    result = [{name: '（mm）'}] + [{name: value[0]} for value in data_processed]
    return result


# 将数据合并
def combined_data(data, predict_train, predict_validation,  predict_60_plot):
    combined_list = []

    for i in range(len(data)):
        dict1 = data[i]
        dict2 = predict_train[i]
        dict3 = predict_validation[i]
        dict4 = predict_60_plot[i]
        combined_dict = {**dict1, **dict2, **dict3, **dict4}
        combined_list.append(combined_dict)

    return combined_list


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '-p', '--port',
        type=int,
        default=5000,
        help='Port of serving api')
    args = parser.parse_args()
    app.run(host='0.0.0.0', port=args.port)
